import React, { useState, useEffect } from "react";
import Taro, {
  getCurrentInstance,
  useDidShow,
  useShareAppMessage,
} from "@tarojs/taro";
import { View, Text, Image, Button } from "@tarojs/components";
import { AtTabs, AtTabsPane, AtImagePicker, AtTextarea } from "taro-ui";

import api from "@api/api.js";
import { uploadImgs } from "@util/util";

import Plan from "./plan";
import Patient from "./patient";
import Blood from "./blood";
import Price from "./price";
import Footer from "./footer";
import Show from "./show";
import Department from "./department";
import "./index.less";

export default () => {
  const [type, setType] = useState(""); // 判断进入当前页面的人 expert专家 patient患者
  const [tabList, setTabList] = useState([
    { title: "诊断资料" },
    { title: "诊断方案" },
    { title: "会诊方案" },
  ]);
  const [hasExpertsDiag, setHasExpertsDiag] = useState(false); // 是否邀请了专家会诊
  const [sysParam, setSysParam] = useState({ order_sex: [] }); // 数据字典
  const [current, setCurrent] = useState(0); // 当前tab页
  const [id, setId] = useState(""); // 方案id
  const [clinicSchemesId, setClinicSchemesId] = useState(""); // 科室方案id
  const [tooth, setTooth] = useState([]); // 牙位
  const [patientInfo, setPtInfo] = useState({}); // 客户信息
  const [diagnosisInfo, setDsInfo] = useState({}); //诊断信息
  const [counselorInfo, setCrInfo] = useState({}); //医生信息
  const [planInfo, setPlanInfo] = useState({}); // 手术信息
  const [deptList, setDeptList] = useState([]); // 科室列表
  const [priceInfo, setPriceInfo] = useState({}); // 价格方案
  const [simpleInfo, setSimpleInfo] = useState({}); // 价格总计
  useEffect(() => {
    getSysParam(() => {
      const type = getCurrentInstance().router.params.type;
      type ? setType(type) : "";
      if (type == "expert") {
        Taro.setNavigationBarTitle({
          title: "专家录入",
        });
        setTabList([{ title: "诊断资料" }, { title: "诊断方案" }]);
      }
      const id = getCurrentInstance().router.params.id;
      // const id = "30e86ba8690fa0c2a16c948ff4db8ee3";
      if (id) {
        getDtl(id);
        setId(id);
        const csId = getCurrentInstance().router.params.clinicSchemesId;
        if (csId) {
          changCurrentfn(1, id, csId);
          setClinicSchemesId(csId);
        }
      }
    });
  }, []);
  // 获取数据字典
  const getSysParam = async (fn) => {
    const { data } = await api.getSysParam([
      "order_sex",
      "diag_status",
      "paymentTimesType",
      "PaymentSchemes_discountRate",
    ]);
    setSysParam(data);
    fn();
  };
  // 获取诊断资料详情
  const getDtl = async (id) => {
    const {
      data: {
        patient,
        hasExpertsDiag,
        diagnosisData,
        diagnosisData: { imagingDataList, xrayDataList },
        counselor,
      },
    } = await api.getDiagnosisDataDetail(id);
    // 图片回显
    const res = imagingDataList
      ? imagingDataList.map((item) => ({
          url: api.bseUrl + item.path,
          id: item.id,
        }))
      : [];
    const resX = xrayDataList
      ? xrayDataList.map((item) => ({
          url: api.bseUrl + item.path,
          id: item.id,
        }))
      : [];
    setPtInfo(patient);
    setDsInfo({ ...diagnosisData, imagingDataList: res, xrayDataList: resX });
    setCrInfo(counselor);
    setHasExpertsDiag(hasExpertsDiag);
  };
  // 获取科室列表
  const department = async (id, current, csId) => {
    // 判断专家type == "expert"进入 current == 2会诊方案
    const { data, code } = await (type == "expert" || current == 2
      ? api.getClinics(id)
      : api.getDepartmentList(id));
    if (code == 200 && data) {
      setDeptList(data);
      if (csId) {
        for (const i in data) {
          if (data[i].clinicSchemesId == csId) {
            useDepFn(data[i].clinicSchemesId, id);
            setTooth(data[i]);
            return false;
          } else {
            setPlanInfo({});
            setTooth([]);
          }
        }
      } else {
        for (const i in data) {
          if (data[i].hasClinicSchemes) {
            useDepFn(data[i].clinicSchemesId);
            setTooth(data[i]);
            return false;
          } else {
            setPlanInfo({});
            setTooth([]);
          }
        }
      }
    } else {
      setClinicSchemesId("");
      setPlanInfo({});
    }
  };
  // 获取科室方案详情
  const getClinicSchemesDetail = async (csId, id) => {
    const { data } = await api.getClinicSchemesDetail(csId);
    getSimpleInfo(id);
    setPlanInfo({ ...data });
  };
  // 获取科室价格方案
  const getPricingSchemes = async (id) => {
    const { data } = await api.getPricingSchemes(id);
    setPriceInfo(data);
  };
  // 获取价格总计
  const getSimpleInfo = async (paramId) => {
    const { data } = await api.getSimpleInfo(paramId ? paramId : id);
    setSimpleInfo(data);
  };
  // 客户信息输入监听
  const savePatientInfo = (key, value) => {
    setPtInfo({ ...patientInfo, [key]: value });
  };
  // 保存患者信息
  const saveUser = async (fn) => {
    const { data, code, errorMessage } = await api.savePatientInfo({
      ...patientInfo,
      gender: patientInfo.genderCode,
    });
    if (code == 200) {
      setId(data);
      fn && fn(data);
    } else {
      Taro.showToast({
        title: errorMessage,
        icon: "none",
      });
    }
  };
  // 诊断资料输入监听
  const saveDiagnosisData = (key, value) => {
    setDsInfo({ ...diagnosisInfo, [key]: value });
  };
  // 手术信息输入监听
  const savePlanInfo = (key, index, value) => {
    const { surgicalSchemesList } = planInfo;
    surgicalSchemesList[index][key] = value;
    setPlanInfo({ ...planInfo });
  };
  // 保存诊断资料
  const saveDiagnosis = () => {
    saveUser(async (pramId) => {
      const { imagingDataList, xrayDataList } = diagnosisInfo;
      const [imagingDataIds, xrayDataIds] = await Promise.all([
        uploadImgs(imagingDataList),
        uploadImgs(xrayDataList),
      ]);
      const { code } = await api.saveDiagnosisData({
        ...diagnosisInfo,
        imagingDataIds,
        xrayDataIds,
        diagnosisSchemesId: pramId ? pramId : id,
      });
      if (code == 200) {
        Taro.showToast({
          title: "保存成功",
          icon: "none",
        });
      } else {
        Taro.showToast({
          title: errorMessage,
          icon: "none",
        });
      }
    });
  };
  // 保存诊断信息
  const savePlan = async (type) => {
    const { surgicalSchemesList } = planInfo;
    const arr = [];
    surgicalSchemesList &&
      surgicalSchemesList.map((item) => {
        return arr.push({
          surgicalSchemesId: item.surgicalSchemesId,
          surgicalDetail: {
            numberOfDiag: item.numberOfDiag,
            remarks: item.remarks,
          },
        });
      });
    const { code } = await api.saveSurgicalDetailList({
      surgicalList: arr,
    });
    if (code == 200) {
      type &&
        Taro.showToast({
          title: "保存成功",
          icon: "none",
          duration: 2000,
        });
    }
  };
  // 图片上传
  const uploadImg = (type, file) => {
    diagnosisInfo[type] = file;
    setDsInfo({ ...diagnosisInfo });
  };
  const failImg = (msg) => {
    console.log(msg);
  };
  const deleteImg = (index, file) => {
    console.log(index, file);
  };
  // tab切换事件
  const changCurrent = (value) => {
    id
      ? changCurrentfn(value, id)
      : saveUser((id) => {
          changCurrentfn(value, id);
        });
  };
  // tab切换渲染
  const changCurrentfn = (value, id, csId = "") => {
    setCurrent(value);
    value == 1 && getSimpleInfo(id);
    value != 0 && department(id, value == 2 ? value : "", csId);
  };
  // 跳转选择牙位
  const goSelectTooth = (params) => {
    if (!params.hasClinicSchemes) {
      Taro.navigateTo({
        url: `/pages/select-tooth/index?id=${id}&isChild=${params.childTooth}&clinicId=${params.clinicId}&type=${type}`,
      });
    } else {
      setTooth(params);
      useDepFn(params.clinicSchemesId);
    }
  };
  // 跳转修改牙位
  const goEditTooth = () => {
    Taro.navigateTo({
      url: `/pages/select-tooth/index?id=${id}&isChild=${
        tooth.childTooth
      }&clinicSchemesId=${clinicSchemesId}&clinicId=${
        tooth.clinicId
      }&tooth=${JSON.stringify(tooth.toothPosition)}&type=${type}`,
    });
  };

  // 价格改变要请求的接口
  const usePriceFn = (clinicSchemesId) => {
    getSimpleInfo();
    getPricingSchemes(clinicSchemesId);
  };
  // 科室改变后需要请求的接口
  const useDepFn = (clinicSchemesId, id = "") => {
    setClinicSchemesId(clinicSchemesId);
    getClinicSchemesDetail(clinicSchemesId, id);
    getPricingSchemes(clinicSchemesId);
  };

  useShareAppMessage((res) => {
    if (res.from === "button") {
      const type = res.target.dataset.type;
      return {
        title: `诊断方案`,
        path: `/pages/add/index?type=${type ? type : ""}&id=${id}`,
      };
    }
  });

  return (
    <View className="bgBox">
      <View className="titleBox">
        <Text className="title">患者信息</Text>
        <Text className="dec">第1次就诊</Text>
        <View className="history">
          <Text className="font">查看历史方案</Text>
        </View>
      </View>
      {/* 患者信息 */}
      <View className="listBox patient">
        <Patient
          data={patientInfo}
          change={savePatientInfo}
          sysParam={sysParam}
        />
      </View>
      {/* 诊断信息 */}
      <View className="listBox information">
        <AtTabs
          current={current}
          swipeable={false}
          onClick={changCurrent.bind(this)}
          tabList={tabList}
        >
          <AtTabsPane current={current} index={0}>
            {/* 医生信息 */}
            <View className="doctor borderBottom myButton">
              <Image src={api.bseUrl + counselorInfo.headimgurl} />
              <View className="name fontBold">
                {counselorInfo.name}
                <View className="font">{counselorInfo.position}</View>
              </View>
              <Button className="send font" openType="share">
                发送方案给医生
              </Button>
            </View>
            {/* 患者主诉 */}
            <View className="mainSuit borderBottom">
              <View className="fontBold">患者第一主诉</View>
              <AtTextarea
                value={diagnosisInfo.dictation}
                count={false}
                name="dictation"
                height="100"
                placeholderClass="font"
                placeholder="请输入患者第一主诉"
                onChange={saveDiagnosisData.bind(this, "dictation")}
              />
            </View>
            {/* 资料上传 */}
            <View className="dataUpload borderBottom">
              <View className="title at-row">
                <View className="fontBold at-col at-col-1 at-col--auto">
                  资料上传
                </View>
                <View className="font at-col at-col-1 at-col--auto">
                  影像资料（建议包括正面、侧面、上颌、下颌）
                </View>
              </View>
              <View className="upload at-row">
                <View className="fontBold at-col at-col-1 at-col--auto">
                  资料上传
                </View>
                <View className="at-col">
                  <View className="img">
                    <AtImagePicker
                      multiple
                      length={3}
                      files={diagnosisInfo.imagingDataList}
                      onChange={uploadImg.bind(this, "imagingDataList")}
                      onFail={failImg.bind(this)}
                      onImageClick={deleteImg.bind(this)}
                    />
                  </View>
                  <View className="font">X光片</View>
                  <View className="img">
                    <AtImagePicker
                      multiple
                      length={3}
                      files={diagnosisInfo.xrayDataList}
                      onChange={uploadImg.bind(this, "xrayDataList")}
                      onFail={failImg.bind(this)}
                      onImageClick={deleteImg.bind(this)}
                    />
                  </View>
                </View>
              </View>
            </View>
            {/* 血糖血压 */}
            <Blood data={diagnosisInfo} change={saveDiagnosisData} />
          </AtTabsPane>
          <AtTabsPane current={current} index={1}>
            {current == 1 && (
              <>
                <Department
                  deptList={deptList}
                  clinicSchemesId={clinicSchemesId}
                  goSelectTooth={goSelectTooth}
                  show={type == "patient" ? true : false}
                />
                {clinicSchemesId && (
                  <View className="tooth">
                    <View className="toothTitle fontBold">牙位</View>
                    <View className="toothList">
                      {tooth.toothPosition &&
                        tooth.toothPosition.map((item) => {
                          return <Text>{item}</Text>;
                        })}
                    </View>
                    {type != "patient" && (
                      <View className="fontBlue" onclick={goEditTooth}>
                        编辑
                      </View>
                    )}
                  </View>
                )}
              </>
            )}
          </AtTabsPane>
          <AtTabsPane current={current} index={2}>
            {current == 2 && hasExpertsDiag && (
              <>
                {deptList && (
                  <Department
                    deptList={deptList}
                    clinicSchemesId={clinicSchemesId}
                    goSelectTooth={goSelectTooth}
                    show={true}
                  />
                )}
                {tooth.toothPosition && (
                  <View className="tooth">
                    <View className="toothTitle fontBold">牙位</View>
                    <View className="toothList">
                      {tooth.toothPosition &&
                        tooth.toothPosition.map((item) => {
                          return <Text>{item}</Text>;
                        })}
                    </View>
                  </View>
                )}
              </>
            )}
          </AtTabsPane>
        </AtTabs>
      </View>
      {/* 诊断方案 */
      current == 1 && clinicSchemesId && (
        <>
          {type == "patient" ? (
            <View className="showList">
              <Show planInfo={planInfo} type={type} />
            </View>
          ) : (
            <>
              <Plan
                clinicSchemesId={clinicSchemesId}
                list={planInfo.surgicalSchemesList}
                counselorInfo={counselorInfo}
                useDepFn={useDepFn}
                savePlan={savePlan}
                savePlanInfo={savePlanInfo}
                getClinicSchemesDetail={getClinicSchemesDetail}
              />
            </>
          )}
          <Price
            type={type}
            clinicSchemesId={clinicSchemesId}
            priceInfo={priceInfo}
            usePriceFn={usePriceFn}
          />
        </>
      )}
      {/* 专家会诊 */
      current == 2 && clinicSchemesId && hasExpertsDiag && (
        <Show planInfo={planInfo} />
      )}
      {
        /* 保存方案 */
        <Footer
          current={current}
          onchange={() => {
            current == 0 ? saveDiagnosis() : savePlan(true);
          }}
          id={id}
          type={type}
          sysParam={sysParam}
          clinicSchemesId={clinicSchemesId}
          hasExpertsDiag={hasExpertsDiag}
          simpleInfo={simpleInfo}
          getSimpleInfo={getSimpleInfo}
        />
      }
    </View>
  );
};
